<template>
    <div>
        <!-- 面包屑导航区 -->
        <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>添加商品</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 内容卡片区 -->
        <el-card>
            <el-alert title="添加商品信息" type="info" show-icon center :closable="false"></el-alert>
            <!-- 步骤 -->
            <el-steps :space="200" :active="Number(active)" finish-status="success" align-center>
                <el-step v-for="(title,id) in steps" :title="title" :key="id"></el-step>
            </el-steps>
            <!-- form表单 -->
            <el-form :model="addForm" :rules="formRules" ref="addFormRef" label-width="100px" label-position="top">
                <!-- tab -->
                <el-tabs tab-position="left" v-model="active" :before-leave="beforeTabLeave">
                    <el-tab-pane label="基本信息" name="0">
                        <el-form-item label="商品名称" prop="goods_name">
                            <el-input v-model="addForm.goods_name"></el-input>
                        </el-form-item>
                        <el-form-item label="商品价格" prop="goods_price">
                            <el-input v-model="addForm.goods_price" type="number"></el-input>
                        </el-form-item>
                        <el-form-item label="商品重量" prop="goods_weight">
                            <el-input v-model="addForm.goods_weight" type="number"></el-input>
                        </el-form-item>
                        <el-form-item label="商品数量" prop="goods_number">
                            <el-input v-model="addForm.goods_number" type="number"></el-input>
                        </el-form-item>
                        <el-form-item label="商品分类" prop="goods_cat">
                            <el-cascader v-model="addForm.goods_cat" :options="cateList" clearable
                                :props="cascaderProps" @change="cateChanged">
                            </el-cascader>
                        </el-form-item>
                    </el-tab-pane>
                    <el-tab-pane label="商品参数" name="1">
                        <!-- 商品参数 -->
                        <el-form-item v-for="item in addForm.goods_many_attrs" :label="item.attr_name" :key="item.attr_id">
                            <el-checkbox-group v-model="item.attr_vals">
                                <el-checkbox v-for="(val,id) in item.attr_vals" :label="val" :key="id"
                                    border></el-checkbox>
                            </el-checkbox-group>
                        </el-form-item>
                    </el-tab-pane>
                    <el-tab-pane label="商品属性" name="2">
                        <!-- 商品属性 -->
                        <el-form-item v-for="item in addForm.goods_only_attrs" :label="item.attr_name" :key="item.attr_id">
                            <el-input v-model="item.attr_vals"></el-input>
                        </el-form-item>
                    </el-tab-pane>
                    <el-tab-pane label="商品图片" name="3">
                        <!-- 上传图片区 -->
                        <el-upload :action="uploadURL" :on-preview="handlePreview" :on-remove="handleRemove"
                            list-type="picture" :headers="headersObj" :on-success="handleUploadSuccess">
                            <el-button size="small" type="primary">点击上传</el-button>
                        </el-upload>
                    </el-tab-pane>
                    <el-tab-pane label="商品内容" name="4">
                        <!-- 商品内容 -->
                        <quill-editor v-model="addForm.goods_introduce">
                        </quill-editor>
                        <el-button type="primary" class="btn-submit" @click="addGoods">提交</el-button>
                    </el-tab-pane>
                </el-tabs>
            </el-form>
        </el-card>
        <!-- 图片预览对话框 -->
        <el-dialog title="图片预览" :visible.sync="previewVisible" width="50%">
            <img :src="previewPath" class="preview-image">
        </el-dialog>
    </div>
</template>

<script>
export default {
    data() {
        return {
            steps: ['基本信息', '商品参数', '商品属性', '商品图片', '商品内容', '完成'],
            active: 0,
            addForm: {
                goods_name: '',
                goods_price: 0,
                goods_number: 0,
                goods_weight: 0,
                goods_cat: [],
                pics: [],
                goods_introduce: '',
                attrs: [],
                // 商品动态参数列表 
                goods_many_attrs: [],
                // 商品属性列表
                goods_only_attrs: [],
            },
            formRules: {
                goods_name: [
                    { required: true, message: '请输入商品名称', trigger: 'blur' },
                    { min: 2, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
                ],
                goods_price: [
                    { required: true, message: '请输入商品价格', trigger: 'blur' },
                ],
                goods_weight: [
                    { required: true, message: '请输入商品重量', trigger: 'blur' },
                ],
                goods_number: [
                    { required: true, message: '请输入商品数量', trigger: 'blur' },
                ],
                goods_cat: [
                    { required: true, message: '请输入商品分类', trigger: 'blur' },
                ],
            },
            // 商品分类列表
            cateList: [],
            // 级联选择器属性类
            cascaderProps: {
                expandTrigger: 'hover',
                value: 'cat_id',
                label: 'cat_name',
                children: 'children'
            },
            uploadURL: 'http://127.0.0.1:8888/api/private/v1/upload',
            // 上传图片的请求头
            headersObj: {
                Authorization: sessionStorage.getItem("token")
            },
            previewPath: '',
            previewVisible: false
        }
    },
    created() {
        this.getCateList()
    },
    computed: {
        cateId() {
            if (this.addForm.goods_cat.length === 3) {
                return this.addForm.goods_cat[2]
            }
            return null
        }
    },
    methods: {
        getCateList() {
            this.$http({
                url: 'categories',
                method: 'get',
            }).then((res) => {
                this.cateList = res.data
            })
        },
        // 获取商品参数和商品属性列表
        getDataList(type) {
            this.$http({
                url: `categories/${this.cateId}/attributes`,
                method: 'get',
                params: { sel: type }
            }).then((res) => {
                if (res.meta.status === 200) {
                    console.log(res.data);
                    if (type === 'many') {
                        res.data.forEach(ele => {
                            ele.attr_vals = ele.attr_vals ? ele.attr_vals.split(' ') : []
                        })
                        this.addForm.goods_many_attrs = res.data
                    } else {
                        this.addForm.goods_only_attrs = res.data
                    }
                } else {
                    this.$message.error(res.meta.msg)
                }
            })
        },
        cateChanged() {
            console.log(this.addForm.goods_cat);
            if (this.addForm.goods_cat.length !== 3) {
                this.addForm.goods_cat = []
            }
        },
        beforeTabLeave(activeName, oldActiveName) {
            if (oldActiveName === '0' && this.addForm.goods_cat.length !== 3) {
                this.$message.error('请选择商品分类')
                return false
            }
            if (oldActiveName === '3' && this.addForm.pics.length === 0) {
                this.$message.error('请上传商品图片')
                return false
            }
            if (activeName === '1') {
                this.getDataList('many')
            } else if (activeName === '2') {
                this.getDataList('only')
            }
            return true
        },
        // 处理图片预览效果
        handlePreview(file) {
            this.previewPath = file.response.data.url
            this.previewVisible = true
        },
        // 处理移除图片的操作
        handleRemove(file) {
            const tmp_path = file.response.data.tmp_path
            const index = this.addForm.pics.findIndex(item => item.pic === tmp_path)
            this.addForm.pics.splice(index, 1)
            if (file.status === "success") {
                this.$message.success('移除图片成功')
            }
        },
        // 监听图片上传成功事件
        handleUploadSuccess(res) {
            this.addForm.pics.push({ "pic": res.data.tmp_path })
            this.$message.success(res.meta.msg)
            // console.log(this.addForm);
        },
        addGoods() {
            this.$refs.addFormRef.validate( valid => {
                if (valid) {
                    // 数据处理
                    let form = {...this.addForm}
                    form.goods_cat = form.goods_cat.join(',')
                    form.goods_many_attrs.forEach(item => {
                        console.log(item);
                        form.attrs.push({attr_id: item.attr_id, attr_value: item.attr_vals.join(' ')})
                    })
                    form.goods_only_attrs.forEach(item => {
                        form.attrs.push({attr_id: item.attr_id, attr_value: item.attr_vals})
                    })
                    // console.log(this.addForm);
                    // console.log(form);
                    this.$http.post('goods', form).then( res => {
                        if (res.meta.status === 201) {
                            this.$message.success(res.meta.msg)
                            this.$router.push("/goods")
                        } else {
                            this.$message.error(res.meta.msg)
                        }
                    }).catch( error => {
                        console.log(error);
                    })
                } else {
                    this.$message.error("请填写必要的表单项！")
                }
            })
        }
    }

}
</script>

<style lang="less" scoped>
.el-steps {
    margin: 10px 0;
}

.el-checkbox {
    margin: 0 10px 0 0 !important;
}

.preview-image {
    width: 100%;
}

.btn-submit {
    margin-top: 15px;
}

</style>